package com.intelligent.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.intelligent.mapper.DeliveryManagementMapper;
import com.intelligent.pojo.DeliveryManagement;
import com.intelligent.service.DeliveryManagementService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Service
public class DeliveryManagementServiceImpl extends ServiceImpl<DeliveryManagementMapper, DeliveryManagement>
        implements DeliveryManagementService {

    @Override
    public Page<DeliveryManagement> pageList(Integer pageNum, Integer pageSize, String deliveryOrderNo) {
        Page<DeliveryManagement> page = new Page<>(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
        LambdaQueryWrapper<DeliveryManagement> wrapper = new LambdaQueryWrapper<>();
        if (deliveryOrderNo != null && !deliveryOrderNo.isEmpty()) {
            wrapper.like(DeliveryManagement::getDeliveryOrderNo, deliveryOrderNo);
        }
        wrapper.orderByDesc(DeliveryManagement::getId);
        return this.page(page, wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DeliveryManagement create(DeliveryManagement delivery) {
        if (delivery.getApprovalStatus() == null) delivery.setApprovalStatus(1);
        // 临时单号避免非空约束
        String tmp = "TMP-" + System.currentTimeMillis();
        delivery.setDeliveryOrderNo(tmp);
        this.save(delivery);
        String ym = DateTimeFormatter.ofPattern("yyyyMM").format(LocalDate.now());
        String no = "FH" + ym + String.format("%04d", delivery.getId());
        delivery.setDeliveryOrderNo(no);
        this.updateById(delivery);
        return delivery;
    }

    @Override
    public DeliveryManagement detail(Long id) {
        return this.getById(id);
    }
}


